<template>
  <div class="app-container org">
    <el-card class="leftCard">
      <!-- 搜索条件盒子 -->
      <div>
        <p class="pinformation">搜索条件</p>
        <el-form :model="queryParams" ref="queryRef" label-width="100">
          <el-form-item label="配置包名称：" prop="packageName">
            <el-input v-model="queryParams.packageName" placeholder="请输入配置包名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="适用仪器型号：" prop="instrumentId">
            <el-select v-model="queryParams.instrumentId" clearable filterable remote reserve-keyword
              placeholder="请输入适用仪器型号" remote-show-suffix :remote-method="remoteMethod" :loading="loading1"
              style="width: 100%">
              <el-option v-for="item in instrumentList" :key="item.instrumentId" :value="item.instrumentId"
                :label="item.name + '　' + item.code">
                {{ item.name }}&nbsp;{{ item.code }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="仪器名称：" prop="instrumentName">
                <el-input v-model="queryParams.instrumentName" placeholder="请输入仪器名称" clearable
                  @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-row justify="end">
                <el-button type="success" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div>
        <el-row style="justify-content: space-between">
          <el-row>
            <p class="pinformation">仪器数据配置包列表</p>
            <p class="totalStyle">共 {{ total }} 条数据</p>
          </el-row>
          <div>
            <el-button type="success" link icon="Plus" @click="handeleAdd">新增</el-button>
          </div>
        </el-row>

        <el-table class="business" ref="mainTableRef" v-loading="loading" :data="pagerTable" @row-click="rowClick"
          :row-class-name="tableRowClass">
          <el-table-column label="配置包名称" align="center" prop="packageName" />
          <el-table-column label="仪器型号" align="center" prop="instrumentCode" />
          <el-table-column label="仪器名称" align="center" prop="instrumentName" />
          <el-table-column label="厂商" align="center" prop="madeObject" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80">
            <template #default="scope">
              <el-button link type="success" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </el-card>

    <el-card class="rightCard">
      <!-- 基础信息 -->
      <el-form :model="form" :rules="rules" ref="serialRef">
        <p class="pinformation">基础信息</p>
        <el-row>
          <el-col :span="6">
            <el-form-item label="仪器数据配置包名称：" prop="packageName">
              <el-input clearable v-model="form.packageName" placeholder="请输入仪器数据配置包名称" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="适用仪器型号：" prop="instrumentId">
              <el-select style="width: 100%" v-model="form.instrumentId" clearable filterable remote reserve-keyword
                placeholder="请输入适用仪器型号" remote-show-suffix :remote-method="remoteMethod1" @change="instrumentIdChange"
                :loading="loading2">
                <el-option v-for="(item, index) in instrumentList1" :key="item.instrumentId" :value="item.instrumentId"
                  :label="item.name + '　' + item.code">
                  {{ item.name }}&nbsp;{{ item.code }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="　生产厂商："> {{ madeObject }} </el-form-item>
          </el-col>
          <el-col :span="1" style="padding-top: 5px">
            <el-button type="success" size="small" @click="submitForm(false)">保存</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="16">
            <el-row>
              <p class="pinformation" style="margin-top: 8px">
                文字识别字段列表
              </p>
              <p class="totalStyle" style="margin-top: 5px">
                共 {{ pagerConfigList.length }} 条数据
              </p>
              <el-row style="margin-left: 20px">
                <el-button type="success" link icon="Plus" @click="addPagerButton">新增</el-button>
                <el-button link type="success" @click.stop="handleCopy()">复制</el-button>
              </el-row>
            </el-row>
            <el-table ref="subTableRef" :data="pagerConfigList">
              <el-table-column label="识别文字" align="center" prop="dataText" />
              <el-table-column label="间隔标识" align="center" prop="dataIntvlSign" />
              <el-table-column label="对应数值标识" align="center" prop="dataNumSign" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="success" @click="copypagerConfigList(scope.row.dataId)">复制</el-button>
                  <el-button link type="success" @click="editpagerConfigList(scope.row.dataId)">编辑</el-button>
                  <el-button link type="success" @click="deletepagerConfigList(scope.row.dataId)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="8">
            <p class="pinformation">打印纸条示例</p>
            <fileUpload v-model="form.fileList" :fileType="['png', 'jpg']"></fileUpload>
          </el-col>
        </el-row>
        <el-row>
          <p class="pinformation" style="margin-top: 8px">原始记录对应列表</p>
          <p class="totalStyle" style="margin-top: 5px">
            共 {{ recordsConfigList.length }} 条数据
          </p>
          <el-row style="margin-left: 20px">
            <el-button type="success" link icon="Plus" @click="addRecordButton">新增</el-button>
          </el-row>
        </el-row>
        <el-table ref="sub1TableRef" :data="recordsConfigList">
          <el-table-column label="模板编号" align="center" prop="tableCode" />
          <el-table-column label="模板名称" align="center" prop="tableName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="success" @click="editRecordsConfigList(scope.row)">编辑</el-button>
              <el-button link type="success" @click="deleteRecordsConfigList(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <!-- 固定字段弹出框 -->
      <el-dialog :class="'el-dialog-theme3'" :title="title" v-model="sbwzOpen" append-to-body draggable
        :close-on-click-modal="false" @close="dialogClose">
        <el-form :model="addPagerForm" label-width="110" :rules="dialogRules" ref="SerialFormRef">
          <el-form-item label="识别文字：" prop="dataText">
            <el-input clearable v-model="addPagerForm.dataText" />
          </el-form-item>
          <el-form-item label="间隔标识：" prop="dataIntvlSign">
            <el-input clearable v-model="addPagerForm.dataIntvlSign" />
          </el-form-item>
          <el-form-item label="对应数值标识：" prop="dataNumSign">
            <el-input clearable v-model="addPagerForm.dataNumSign" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="save" type="success">保 存</el-button>
            <el-button @click="sbwzOpen = false" type="danger">关 闭</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog :class="'el-dialog-theme3'" :title="ysjlTitle" v-model="ysjlOpen" append-to-body
        draggable :close-on-click-modal="false" @close="dialogClose1">
        <el-form :model="addRecordsForm" label-width="85" :rules="dialogRules" ref="mbFormRef">
          <el-form-item label="模板：" prop="tableId">
            <el-select v-model="addRecordsForm.tableId" clearable filterable style="width: 100%" @change="tableIdChange">
              <el-option v-for="item in templeList" :key="item.tableId" :value="item.tableId"
                :label="item.tableCode + '　' + item.tableName"></el-option>
            </el-select>
          </el-form-item>
          <p class="pinformation">对应关系</p>
          <el-table :data="addRecordsForm.templateList" height="50vh">
            <el-table-column label="识别文字" align="center" prop="dataText" />
            <el-table-column label="原始记录字段" align="center" prop="dataText">
              <template #default="scope">
                <el-select v-model="scope.row.componentId" clearable filterable>
                  <el-option v-for="item in ysjlList" :key="item.componentId" :value="item.componentId"
                    :label="item.componentName"></el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="save1" type="success">保 存</el-button>
            <el-button @click="ysjlOpen = false" type="danger">关 闭</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog :class="'el-dialog-theme3'" title="选择仪器数据配置包" v-model="copyOpen" append-to-body
        draggable :close-on-click-modal="false" @close="copyDialogClose">
        <el-form-item label="仪器数据配置包：" prop="dataNumSign">
          <el-select v-model="cPId" clearable filterable style="width: 100%">
            <el-option v-for="item in pagerList" :key="item.cPId" :value="item.cPId"
              :label="item.packageName"></el-option>
          </el-select>
        </el-form-item>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="copySave" type="success">保 存</el-button>
            <el-button @click="copyOpen = false" type="danger">关 闭</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup name="PagerConfig">
import {
  listPager,
  getPager,
  delPager,
  delPagerConfig,
  getPagerConfigForm,
  addPager,
  listTextConfig,
  addPagerConfig,
  getSelection,
  listRecordsConfig,
  addRecordsConfig,
  delRecordsConfig,
  getRecordsConfigForm,
  listTemple,
  listYsjlZd,
  copyPager,
  getPagerList,
} from "@/api/system/pagerConfig";
import { showImageAPI } from "@/api/resource/instrumentItem";
const { proxy } = getCurrentInstance();

const { sys_code_apply, sys_config_type } = proxy.useDict(
  "sys_code_apply",
  "sys_config_type"
);

const loading = ref(true);
const total = ref(0);
const pagerTable = ref([]);
const sbwzOpen = ref(false);
const title = ref("");
const pagerConfigList = ref([]);
const recordsConfigList = ref([]);

const data = reactive({
  form: { fileList: [] },
  addPagerForm: {},
  addRecordsForm: { templateList: [] },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    packageName: [
      {
        required: true,
        message: "仪器数据配置包名称不能为空",
        trigger: "blur",
      },
    ],
    instrumentId: [
      { required: true, message: "适用仪器型号不能为空", trigger: "blur" },
    ],
  },
  dialogRules: {
    dataIntvlSign: [
      { required: true, message: "间隔标识不能为空", trigger: "blur" },
    ],
    dataText: [
      { required: true, message: "识别文字不能为空", trigger: "blur" },
    ],
    tableId: [{ required: true, message: "模板不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules, addRecordsForm, addPagerForm, dialogRules } =
  toRefs(data);

/** 查询流水号配置列表 */
function getList() {
  loading.value = true;
  listPager(queryParams.value).then((response) => {
    pagerTable.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm("serialRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 修改按钮操作 */
function rowClick(row) {
  reset();
  getPager(row.cPId).then((response) => {
    heightBright.value = row.cPId;
    form.value = response.data;
    if (!form.value.fileList) {
      form.value.fileList = [];
    }
    instrumentList1.value = [
      {
        name: form.value.instrumentName,
        code: form.value.instrumentCode,
        instrumentId: form.value.instrumentId,
      },
    ];
    madeObject.value = form.value.madeObject;
    getTextList();
    getRecordList();
  });
}

/** 提交按钮 */
function submitForm(isAuto) {
  return new Promise((resolve) => {
    proxy.$refs["serialRef"].validate((valid) => {
      if (valid) {
        addPager(form.value).then((res) => {
          if (!isAuto) {
            proxy.$modal.msgSuccess(res.msg);
          }
          form.value.cPId = res.data;
          heightBright.value = res.data;
          getList();
          resolve();
        });
      }
    });
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const cPId = row.cPId;
  proxy.$modal
    .confirm('是否确认删除流水号配置编号为"' + cPId + '"的数据项？')
    .then(function () {
      return delPager(cPId);
    })
    .then(() => {
      getList();
      handeleAdd();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function save() {
  proxy.$refs["SerialFormRef"].validate((valid) => {
    if (valid) {
      addPagerForm.value.cPId = form.value.cPId;
      addPagerConfig(addPagerForm.value).then((res) => {
        sbwzOpen.value = false;
        proxy.$modal.msgSuccess(res.msg);
        getTextList();
      });
    }
  });
}

function getTextList() {
  listTextConfig({ cPId: form.value.cPId }).then((res) => {
    pagerConfigList.value = res.data;
  });
}

function addPagerButton() {
  submitForm(true).then(() => {
    sbwzOpen.value = true;
    title.value = "新增文字识别字段";
  });
}

function deletepagerConfigList(row) {
  proxy.$modal
    .confirm("是否确认删除此条数据项？")
    .then(function () {
      return delPagerConfig(row);
    })
    .then(() => {
      getTextList();
      getRecordList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function editpagerConfigList(row) {
  getPagerConfigForm(row).then((res) => {
    addPagerForm.value = res.data;
    sbwzOpen.value = true;
    title.value = "编辑文字识别字段";
  });
}

function save1() {
  proxy.$refs["mbFormRef"].validate((valid) => {
    if (valid) {
      addRecordsForm.value.cPId = form.value.cPId;
      addRecordsConfig(addRecordsForm.value).then((res) => {
        ysjlOpen.value = false;
        proxy.$modal.msgSuccess(res.msg);
        getRecordList();
      });
    }
  });
}

function getRecordList() {
  listRecordsConfig({ cPId: form.value.cPId }).then((res) => {
    recordsConfigList.value = res.data;
  });
}

const ysjlOpen = ref(false);
const ysjlTitle = ref("");

function addRecordButton() {
  submitForm(true).then(() => {
    ysjlOpen.value = true;
    ysjlTitle.value = "新增原始记录";
    listTemple().then((res) => {
      templeList.value = res.data;
    });
    addRecordsForm.value.templateList = pagerConfigList.value;
  });
}

function deleteRecordsConfigList(row) {
  proxy.$modal
    .confirm("是否确认删除此条数据项？")
    .then(function () {
      return delRecordsConfig(row.tableId, form.value.cPId);
    })
    .then(() => {
      getRecordList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function editRecordsConfigList(row) {
  getRecordsConfigForm(row.tableId, form.value.cPId).then((res) => {
    addRecordsForm.value = res.data;
    tableIdChange(addRecordsForm.value.tableId);
    listTemple().then((res) => {
      templeList.value = res.data;
    });
    ysjlOpen.value = true;
    ysjlTitle.value = "编辑原始记录";
  });
}

function handeleAdd() {
  pagerConfigList.value = [];
  recordsConfigList.value = [];
  addPagerForm.value = {};
  addRecordsForm.value = { templateList: [] };
  heightBright.value = "";
  proxy.resetForm("serialRef");
  form.value.fileList = [];
  delete form.value.cPId;
}

function dialogClose() {
  addPagerForm.value = {};
  proxy.$refs.SerialFormRef.clearValidate();
}

function dialogClose1() {
  addRecordsForm.value = { templateList: [] };
  templeList.value = [];
  ysjlList.value = [];
  proxy.$refs.mbFormRef.clearValidate();
}

getList();

// -------------------------------------远程搜索仪器型号-----------------------------------
const loading1 = ref(false);
const instrumentList = ref([]);
function remoteMethod(val) {
  if (val) {
    loading1.value = true;
    setTimeout(() => {
      getSelection({ instrumentCode: val }).then((res) => {
        loading1.value = false;
        instrumentList.value = res.data;
      });
    }, 200);
  } else {
    instrumentList.value = [];
  }
}

const loading2 = ref(false);
const instrumentList1 = ref([]);
function remoteMethod1(val) {
  if (val) {
    loading2.value = true;
    setTimeout(() => {
      getSelection({ instrumentCode: val }).then((res) => {
        loading2.value = false;
        instrumentList1.value = res.data;
      });
    }, 200);
  } else {
    instrumentList1.value = [];
  }
}

const madeObject = ref("");

function instrumentIdChange(val) {
  if (!val) {
    madeObject.value = "";
    return;
  }
  getSelection({ instrumentId: val }).then((res) => {
    madeObject.value = res.data[0].madeObject;
  });
}

const ysjlList = ref([]);
const templeList = ref([]);
const cPId = ref("");
const pagerList = ref([]);

function tableIdChange(val) {
  listYsjlZd(val).then((res) => {
    ysjlList.value = res.data;
  });
}

//   -----------------------------------------复制功能---------------------------------------
const copyOpen = ref(false);
function handleCopy() {
  submitForm(true).then(() => {
    copyOpen.value = true;
    getPagerList({ cPId: form.value.cPId }).then((res) => {
      pagerList.value = res.data;
    });
  });
}

function copyDialogClose() {
  pagerList.value = [];
  cPId.value = "";
}

function copySave() {
  copyPager({ cPId: form.value.cPId, copyCPId: cPId.value }).then((res) => {
    pagerConfigList.value = res.data;
    proxy.$modal.msgSuccess("复制成功");
    copyOpen.value = false;
  });
}

function copypagerConfigList(dataId) {
  getPagerConfigForm(dataId).then((res) => {
    addPagerForm.value = res.data;
    delete addPagerForm.value.dataId;
    sbwzOpen.value = true;
    title.value = "复制文字识别字段";
  });
}

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [
        { tableName: "main", bottomHeight: 74 },
        { tableName: "sub", bottomHeight: 360 },
        { tableName: "sub1", bottomHeight: 21 },
      ];
    } else {
      heightParams.value = [
        { tableName: "main", bottomHeight: 21 },
        { tableName: "sub", bottomHeight: 360 },
        { tableName: "sub1", bottomHeight: 21 },
      ];
    }
    getTableHeight();
  }
);

const heightParams = ref([
  { tableName: "main", bottomHeight: 21 },
  { tableName: "sub", bottomHeight: 360 },
  { tableName: "sub1", bottomHeight: 21 },
]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

const heightBright = ref("");
function tableRowClass({ row }) {
  if (row) {
    if (row.cPId == heightBright.value) {
      return "current-row";
    }
    return "";
  }
}
</script>
